package cn.jishiyu11.xeqb.activity

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.util.Log
import android.view.View
import android.widget.TextView

import com.umeng.analytics.MobclickAgent

import org.json.JSONObject

import java.io.IOException
import java.util.HashMap

import cn.jishiyu11.xeqb.R
import cn.jishiyu11.xeqb.activity.personalCenterActivitys.settingpage.SetUpPasswordActivity
import cn.jishiyu11.xeqb.base.BaseActivity
import cn.jishiyu11.xeqb.http.http.i.DataCallBack
import cn.jishiyu11.xeqb.http.http.i.httpbase.*
import cn.jishiyu11.xeqb.utils.*
import kotlinx.android.synthetic.main.act_login.*
import kotlinx.android.synthetic.main.act_set_up_password.*
import kotlinx.android.synthetic.main.tab_activity_fra.*
import okhttp3.Request
import java.util.regex.Pattern

/**
 * Created by jsy_zj on 2017/6/28.
 * 登录页面
 */
@SuppressLint("ResourceType")
class LogoActivity : BaseActivity(), View.OnClickListener, DataCallBack {

    private var phone = ""

    private var logo_token = ""

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.act_login)
        getNetIP()
        IsUserCanLog()
        findViewById()
        initView()
    }

    private fun IsUserCanLog() {
        if (!TextUtils.isEmpty(SharedPreferencesUtils.get(this, getString(R.string.userNo), "").toString()) &&
                !TextUtils.isEmpty(SharedPreferencesUtils.get(this, getString(R.string.phoneNo), "").toString()) &&
                !TextUtils.isEmpty(SharedPreferencesUtils.get(this, getString(R.string.token), "").toString())
        ) {
            USER_UserNo = SharedPreferencesUtils.get(this,getString(R.string.userNo),"").toString()
            USER_PhoneNo = SharedPreferencesUtils.get(this,getString(R.string.phoneNo),"").toString()
            this.newIntent<MainActivity>()
            finish()
        } else {
            SharedPreferencesUtils.logoutSuccess(this)
            SharedPreferencesUtils.clear(this)
        }
    }

    override fun onClick(v: View) {
        when (v) {
            loan_logo_button_logo//登入按钮
            -> {
                phone = loan_logo_edittext_phone.text.toString()
                if (StringUtil.isNullOrEmpty(phone)) {
                    this.showShortToast("您输入的手机号码不能为空")
                    return
                } else if (!StringUtil.isMobileNO(phone)) {
                    this.showShortToast("您输入的手机号码不正确,请重新输入")
                    loan_logo_edittext_phone!!.setText("")
                    return
                }

                if (loan_logo_edittext_password_code?.text.toString().length > 5) {
                    var map = HashMap<String, Any>()
                    var postMap = HashMap<String, Any>()
                    map.put(getString(R.string.userNo), "")
                    map.put(getString(R.string.phoneNo), phone)
                    map.put(getString(R.string.password), StringUtil.getMD5String(loan_logo_edittext_password_code?.text.toString()))
                    getPostMap(this, USER_LOGIN, map, postMap)
                    logo_token = postMap.get("token").toString()
                    OkHttpManager.postAsync(ANDROID_HTTP, "LOGO_IN", postMap, this)

                } else {
                    this.showShortToast("不能为空，且不得小于6位")
                    loan_logo_edittext_password_code?.setText("")
                }

            }
            act_log_register//注册
            -> {
                intent = Intent(this@LogoActivity, SetUpPasswordActivity::class.java)
                intent!!.putExtra("name", "1")
                startActivity(intent)
            }
            act_log_goback//返回键
            -> finish()
            loan_logo_no_password//忘记密码
            -> {
                intent = Intent(this@LogoActivity, SetUpPasswordActivity::class.java)
                intent!!.putExtra("name", "2")
                intent!!.putExtra("type", 2)
                startActivity(intent)
            }
            agreement_password -> {
            }
        }
    }

    /**
     * 后去外网IP
     * */
    private fun getNetIP() {
        var map = HashMap<String, String>()
        OkHttpManager.postAsync(GET_NET_IP, "GET_NET_IP", map, this)
    }

    override fun findViewById() {

        act_log_goback.setOnClickListener (this)
        loan_logo_button_code!!.setOnClickListener(this)
        loan_logo_button_logo.setOnClickListener(this)
        loan_logo_account_number!!.setOnClickListener(this)
        loan_logo_no_password!!.setOnClickListener(this)
        act_log_register.setOnClickListener(this)//注册

        if (!USER_PhoneNo.isNullOrEmpty()){
            loan_logo_edittext_phone.setText(USER_PhoneNo)
        }
    }

    override fun initView() {
        loan_logo_edittext_phone!!.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}
            override fun afterTextChanged(s: Editable) {
                phone = s.toString()
            }
        })
    }

    override fun requestFailure(request: Request, name: String, e: IOException) {
        when (name) {
            "LOGO_IN"//登录返回值
            -> this.showShortToast(this.getString(R.string.network_timed))
            "getUserLoginAuthorStatus"//登录返回值
            -> this.showShortToast(this.getString(R.string.network_timed))
        }
    }

    override fun requestSuccess(result: String, name: String) {
        var objects: JSONObject? = null
        println("**************************" + result)
        Log.e("***********resule", result)
        when (name) {
            "GET_NET_IP" -> {
                //获得外网IP
                var regex = "\\d+\\.\\d+\\.\\d+\\.\\d+"
                var pattern = Pattern.compile(regex)
                var matcher = pattern.matcher(result)
                if (matcher.find()) {
                    var ip = matcher.group(0)
                    NetIP = ip
                }
            }
            "LOGO_IN" -> {
                //登录
                objects = JSONObject(result)
                if (result.contains("reqData")) {
                    var data = objects.get("reqData").toString()
                    var key = logo_token.substring(16, 32)
                    var keydCode = AESUtils.decrypt(key, data)//解密
                    objects = JSONObject(keydCode)
                    if (objects.get("code").equals("200")) {
                        //登录成功
//                        this.showShortToast(objects.get("msg").toString())
                        var objectdata: JSONObject = objects.get("data") as JSONObject
                        var phoneNo = objectdata.get(getString(R.string.phoneNo)).toString()
                        var userNo = objectdata.get(getString(R.string.userNo)).toString()
                        var isIdCard = objectdata.get(getString(R.string.isIdCard)).toString()
                        var inviteCode:String = ""
                        if (keydCode!!.contains("inviteCode")){
                            inviteCode = objectdata.getString("inviteCode")
                        }
                        SharedPreferencesUtils.put(this, getString(R.string.token), objectdata.get("token").toString())
                        SharedPreferencesUtils.put(this, getString(R.string.phoneNo), phoneNo)
                        SharedPreferencesUtils.put(this, getString(R.string.userNo), userNo)
                        SharedPreferencesUtils.put(this, getString(R.string.personalcenter_isrealname), isIdCard)
                        SharedPreferencesUtils.put(this, getString(R.string.inviteCode), inviteCode)
                        USER_INVICEDCODE = inviteCode
                        USER_UserNo = userNo
                        USER_PhoneNo = phoneNo
                        this.newIntent<MainActivity>()
                        finish()//关闭当前界面

                    } else {
                        this.showShortToast( objects.get("msg").toString())
                    }
                }
            }
        }
    }


    override fun onResume() {
        super.onResume()
        if (!USER_PhoneNo.isNullOrEmpty()){
            loan_logo_edittext_phone.setText(USER_PhoneNo)
        }
        MobclickAgent.onResume(this)
    }

    override fun onPause() {
        super.onPause()
        MobclickAgent.onPause(this)
    }

    override fun onDestroy() {
        super.onDestroy()
    }


}
